from py3db.mysql import MySql
from config.db import DB_CONFIG


class Filter:

    def __init__(self):
        pass

    @classmethod
    def create_connect(cls, database="crawler"):
        return MySql(DB_CONFIG['host'], DB_CONFIG['user'], DB_CONFIG['password'], database)

    def filter(self, filter_data, filter_id):
        db = self.create_connect()
        filter_result = db.select("crawler_filter", ["filter_rule", "filter_value"], condition_dict={
            "id": filter_id
        })
        if len(filter_result) < 1:
            print("无对应过滤规则")
            return filter_data
        else:
            method, value = filter_result[0]
        filter_method = f"filter_{method}"
        db.close_connect()
        return getattr(self, filter_method)(filter_data, value)

    def filter_replace(self, filter_data, filter_value):
        filter_value = filter_value.split("->")
        replaced_str = filter_value[0] if len(filter_value) else ""
        replace_str = filter_value[1] if len(filter_value) > 1 else ""
        return filter_data.replace(replaced_str, replace_str)

    @staticmethod
    def del_illegal_str(content):
        return content.replace("'", r"\'")


if __name__ == '__main__':
    db = Filter.create_connect()
    db2 = Filter.create_connect("bbiquge")
    filter_result = db.select("crawler_filter", ["filter_rule", "filter_value"], condition_dict={
        "id": 2
    })
    chapter_result = db2.select("chapter", ['content'], condition_dict={
        "id": 2
    })
    print(filter_result, chapter_result)
